import shutil
import os

import common


class CovertBili2Mp4Acc:
    bili_dir:str = ""
    output_dir:str = ""
    tmp_output_mp4:str = "output.mp4"
    tmp_output_aac:str = "output.aac"
    def __init__(self, bili_dir: str, output_dir:str):
        self.bili_dir = bili_dir
        self.output_dir = output_dir
        pass

    def clear_mp4_acc(self):
        if os.path.exists(self.tmp_output_mp4):
            os.remove(self.tmp_output_mp4)
        if os.path.exists(self.tmp_output_aac):
            os.remove(self.tmp_output_aac)
        pass

    def deal(self):
        subpaths, subfiles = common.traverse_folders(self.bili_dir)
        for path in subpaths:
            self.deal_single_video(path)

    def deal_single_video(self, video_dir_name):
        if not os.path.exists(video_dir_name):
            return
        output_dir = self.build_output_dir(video_dir_name)
        if not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)
            pass
        self.clear_mp4_acc()
        m4s_files = self.prepare_m4s_files(video_dir_name)
        self.export_mp4(video_dir_name, m4s_files)
        self.export_aac(video_dir_name, m4s_files)
        self.remove_local_m4s_files(m4s_files)
        pass

    def build_output_dir(self, video_dir_name)->str:
        json_name = os.path.join(video_dir_name, "videoInfo.json")
        group_name = common.get_json_var(json_name, "groupTitle")
        return os.path.join(self.output_dir, group_name)
        pass

    def build_output_file(self, video_dir_name)->str:
        json_name = os.path.join(video_dir_name, "videoInfo.json")
        title_name = common.get_json_var(json_name, "title")
        chapter_str = common.get_json_var(json_name, "p")
        chapter = int(chapter_str)
        out_put_name = f"{str(chapter).zfill(4)} {title_name}"
        return out_put_name
        pass
    def prepare_m4s_files(self, video_dir_name)->[]:
        if not os.path.isdir(video_dir_name):
            raise NotADirectoryError(f"路径 {video_dir_name} 不是有效目录")
        _, all_files = common.traverse_folders(video_dir_name)
        m4s_files = []
        for file in all_files:
            if os.path.splitext(file)[1].lower() == '.m4s':
                common.decrypt_m4s(os.path.join(video_dir_name, file), file)
                m4s_files.append(file)
        return m4s_files
    def remove_local_m4s_files(self, m4s_files:[]):
        for file in m4s_files:
            os.remove(file)
        pass

    def export_mp4(self, video_dir_name, m4s_files):
        output_dir = self.build_output_dir(video_dir_name)
        output_file = self.build_output_file(video_dir_name)
        output_mp4_name = os.path.join(output_dir, output_file + ".mp4")
        if os.path.exists(output_mp4_name):
            return
        command_mp4 = f'".\\ffmpeg\\bin\\ffmpeg.exe" -i {m4s_files[0]} -i {m4s_files[1]} -c:v copy -c:a copy {self.tmp_output_mp4}'
        print(command_mp4)
        os.system(command_mp4)
        shutil.copy(self.tmp_output_mp4, output_mp4_name)

        pass
    def export_aac(self, video_dir_name, m4s_files):
        output_dir = self.build_output_dir(video_dir_name)
        output_file = self.build_output_file(video_dir_name)
        output_aac_name = os.path.join(output_dir, output_file + ".aac")
        if os.path.exists(output_aac_name):
            return
        command_mp3 = f'".\\ffmpeg\\bin\\ffmpeg.exe" -i {m4s_files[0]} -i {m4s_files[1]} -c copy {self.tmp_output_aac}'
        print(command_mp3)
        os.system(command_mp3)
        shutil.copy(self.tmp_output_aac, output_aac_name)
        pass

